#include "boss.h"

#include <SDL/SDL_gfxPrimitives.h>
#include "viewport.h"
#include "spriteManager.h"
#include "explodingSprite.h"
#include "hud.h"
#include "bullet.h"
#include "utils.h"

Boss::Boss(const string& n) :
	io(IOManager::getInstance()),
	name(n),
	sprite(new Sprite(name)),
	health(100),
	health_dx (((float)sprite->getFrame()->getWidth()) / 100.0),
	r(0),g(255),b(0),
	dead(false)
{
	sprite->setRestitution(0.1);
	sprite->setFriction(0.4);
	sprite->setMass(1000);
	SpriteManager::getInstance().addObject(sprite);
}

Boss::~Boss()
{
	
}

void Boss::update()
{
	
}

void Boss::draw()
{
	Vector2f offset(Viewport::getInstance().X(),Viewport::getInstance().Y());

	// Draw the health bar (x1,y1)top right to (x2,y2)bottom left
	int x1 = sprite->X()-offset[0] + (health_dx * health);
	int y1 = sprite->Y()-offset[1] - 15;

	int x2 = sprite->X()-offset[0];
	int y2 = sprite->Y()-offset[1] - 5;

	boxRGBA(io.getScreen(),x1,y1,x2,y2,r,g,b,255);
}

void Boss::updateHealth()
{
	float color_dx = 255.0/50.0;

	if(health > 50) {
		r = (100.0 - health) * color_dx;
		g = 255;
	} else if(health <= 50) {
		r = 255;
		g = health * color_dx;
	}
	// cout << "(r,g,b) => (" << r << "," << g << "," << b << ") " << health << endl;
}

Sprite *Boss::getSprite()
{
	return sprite;
}

void Boss::shoot(Vector2f &dir)
{
	if(dynamic_cast<ExplodingSprite *>(sprite))
		return;

	Vector2f pos = sprite->getCenter();
	//pos[0] += rand() % 200 - 100;
	//pos[1] += rand() % 200 - 100;

	// Set initial velocity of the projectile
	dir = (dir * 400);

	Sprite *bullet = new Bullet(pos, dir, "redorb");
	bullet->setOwner(sprite);
	bullet->setIgnoreGravity(true);
	SpriteManager::getInstance().addObject(bullet);
}

void Boss::left()
{
	Vector2f v = sprite->getVelocity();
	if(v[0] > -75) {
		v[0] = -75;
		sprite->setVelocity(v);
	}
}

void Boss::right()
{
	Vector2f v = sprite->getVelocity();
	if(v[0] < 75) {
		v[0] = 75;
		sprite->setVelocity(v);
	}
}

void Boss::jump()
{
	Vector2f v = sprite->getVelocity();
	if(v[1] > -225) {
		v[1] = -225;
		sprite->setVelocity(v);
	}
}

void Boss::addHealth(int x)
{
	health += x;
	updateHealth();
	health = CLAMP(health, 0, 100);
	
	if (health == 0) {
		sprite->setState(STATE_COLLIDING);
		SpriteManager::getInstance().removePuppetController(this);
		SDL_AddTimer(3000, gameOverCallback, NULL);
		dead = true;
	}
}

int Boss::getHealth()
{
	return health;
}
